/*
 * @Author: funlee
 * @Email: i@funlee.cn
 * @Date: 2018-06-10 15:48:28
 * @Description: 第一版实现 
 */
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import moment from 'moment';
import echarts from 'echarts';
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      AreaChart: null, // 面积图
      DateChart: null, // 时间轴
      data: [],  // 原始数据
      date: [],  // 面积图 X 轴数据
      count: [],  // 面积图 Y 轴数据
      dateChartData: [] // 时间轴图表数据
    }
  }
  componentDidMount() {
    const AreaChart = echarts.init(this.AreaChart);
    const DateChart = echarts.init(this.DateChart);
    this.setState({
      AreaChart,
      DateChart
    }, () => this.getData()) 

    DateChart.on('dataZoom', (params) => {
      const { start, end } = params;
      this.filterAreaData(start, end)
    })
  }
  getData() {
    const data = []; // 原始数据
    let value = Math.random() * 100;
    for (var i = 0; i < 1000; i++) {
      value = value + Math.random() * 21 - 10;
      data.push({
        name: moment().add(i, 'days').format('YYYY-MM-DD'),
        value: Math.round(value)
      });
    }
    const dateChartData = [];  // 时间轴图表所需的数据
    data.forEach(d => {
      const { name,value } = d
      dateChartData.push({
        name,
        value:[name, value]
      })
    })
    this.setState({
      data,
      dateChartData
    }, () => this.renderChart())
  }
  renderChart() {
    this.filterAreaData(); // 先过滤数据在渲染
    this.renderDateChart(); // 时间轴--直接渲染
  }
  filterAreaData(start = 0, end = 100) {
    const { data } = this.state;
    const len = data.length; // 总的数据个数

    const startIndex = start === 100 ? len - 1 : parseInt(len * start / 100, 10); // 起点数据的位置,需要判断是否是 100%
    const endIndex = end === 100 ? len - 1 : parseInt(len * end / 100, 10);   // 终点数据的位置，需要判断是否是 100%

    const startData = data[startIndex]; // 起点数据，此处时间格式为：YYYY-MM-DD
    const endData = data[endIndex]; // 终点数据，此处时间格式为：YYYY-MM-DD

    const startTime = moment(startData.name).format('YYYY')
    const endTime = moment(endData.name).format('YYYY')
    
    /**
     * 按照八年间隔来过滤数据
     * 大于八年且数据个数大于八个按年来过滤
     * 小于八年且数据个数大于八个按月来过滤
     * 小于一年按天
     */
    // if(endTime - startTime >= 8 && endIndex - startIndex >= 8) {
      const { date, count } = this.filterYear(data.slice(startIndex, endIndex))
      // debugger
      this.renderAreaChart(date, count)
    // }


    // 最终得到 date = [] 和 count = []
    // this.renderAreaChart(date, count)
  }
  /**
   * 按照年纬度聚合
   */
  filterYear(data) {
    const date = [];
    const count = [];

    // 这种方案得不到具体每一天的值 -- tooltip
    // 得到所有的年份
    // data.forEach(d => {
    //   const year = `${moment(d.name).format('YYYY')}年`;
    //   if(date.indexOf(year) === -1) {
    //     date.push(year)
    //   }
    // })
    // 聚合每个年份的总数 count
    // date.forEach(year => {
    //   let value = 0;
    //   data.forEach(d => {
    //     if (`${moment(d.name).format('YYYY')}年` === year) {
    //       value += d.value;
    //     }
    //   })
    //   count.push(value)
    // })

    data.forEach(d => {
      const year = `${moment(d.name).format('YYYY')}年`;
      // if(date.indexOf(year) === -1) {
      date.push(year)
      // }
      count.push(d.value)
    })

    return {
      date,count
    }
  }
  renderAreaChart(date, count) {
    const { AreaChart } = this.state;
    const option = {
      grid: {
        bottom: '15%' // 调整底部距离
      },
      tooltip: {
        trigger: 'axis',
        position: function (pt) {
          return [pt[0], '10%'];
        }
      },
      xAxis: {
        data: date,
        splitNumber: 7,
        interval: 0,
        axisLine: {
          lineStyle: {
            color: '#fff'
          }
        },
        axisTick: {
          lineStyle: {
            color: '#fff'
          }
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          color: '#fff',
          align: 'center',
          fontSize: 16,
          // formatter: function (value,index) {
          //   if(index % 2 !== 0) {
          //     return 'HH'
          //   } else {
          //     return `T`
          //   }
            
          // }
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        axisLine: {
          lineStyle: {
            color: '#fff'
          }
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          color: '#fff',
          fontSize: 16
        }
      },
      series: [{
        name: '模拟数据',
        type: 'line',
        showSymbol: false,
        hoverAnimation: false,
        data: count
      }]
    }; 
    AreaChart.setOption(option);
  }
  renderDateChart() {
    const { dateChartData, DateChart } = this.state;
    const option = {
      xAxis: {
        type: 'time',
        show: false,
        position: 'top',
        splitNumber: 9,
        axisLine: {
          lineStyle: {
            color: '#fff'
          }
        },
        axisTick: {
          lineStyle: {
            color: '#fff'
          }
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          color: '#fff',
          fontSize: 16,
          formatter: function(value, index) {
            return moment(value).format('YYYY-MM-DD')
          }
        }
      },
      yAxis: {
        show: false
      },
      dataZoom: [{
        type: 'inside'
      },{
        backgroundColor: 'rgba(33,51,103,.1)',
        dataBackground:{
          lineStyle: {
            color: 'rgba(17,54,122,0)'
          },
          areaStyle: {
            color: {
              type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0,
                  color: 'rgba(57,101,155,.8)' // 0% 处的颜色
                }, {
                  offset: 1,
                  color: 'rgba(32,51,100,.8)' // 100% 处的颜色
                }]
            }
          }
        },
        fillerColor: 'rgba(33,51,103,.3)', // 选中范围的填充颜色
        handleStyle: { 
          color: '#0090ff',
        },
        showDetail: true,
        realtime: false,
        textStyle: { // 显示范围
          color: 'red',
          fontSize: 14
        }
      }],
      series: [{
        type: 'line',
        showSymbol: false,
        hoverAnimation: false,
        lineStyle:{
          color: 'rgba(0,0,0,0)'
        },
        data: dateChartData
      }]
    }; 
    DateChart.setOption(option);
  }
  
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
        <div className="chart" ref={e => this.AreaChart = e} style={{width: 1200, height: 600, margin: '20px auto 0'}} />
        <div className="date-chart" ref={e => this.DateChart = e} style={{width: 1200, height: 50}} />
      </div>
    );
  }
}

export default App;
